<template>
  <BasicModal
    :title="getTitle"
    :width="500"
    :canFullscreen="false"
    :centered="true"
    :destroyOnClose="true"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" :model="model" />
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive, watchEffect } from "vue";
import { BasicModal, useModalInner } from "/@/components/Modal";
import { BasicForm, useForm } from "/@/components/Form/index";
import { add, queryById } from "/@/views/weixin/article/artticle.api";
import { useMessage } from "/@/hooks/web/useMessage";
import { select } from "/@/views/weixin/menu/menu.api";
import { isRoleExist } from "/@/views/system/role/role.api";
import { AutoComplete } from "ant-design-vue";

const $message = useMessage();

// 声明Emits
const emit = defineEmits(['success', 'register']);

const labelCol = { span: 6 }
const wrapperCol = { span: 16 }
//表单modal
const model = reactive<any>({})

//表单配置
const [registerForm, {resetFields, setFieldsValue, validate}] = useForm({
  schemas: [
    { label: "", field: "id", component: "Input", show: false },
    { label: "部门", field: "ddlx", component: "JDictSelectTag", required: true,
      componentProps: {
        dictCode: "ddlxType@ddlxUser",
        placeholder: "请选择",
      },
    },
    { label: "所属栏目", field: "menuentityId", component: 'ApiTreeSelect', required: true,
      componentProps: {
        api: select,
        fieldNames: { children: 'children', label: 'name', key: 'id', value: 'id', selectable: 'selectable' },
        dropdownStyle: {
          //maxHeight: '50vh',
        },
        treeDefaultExpandAll:true,
        onSelect: (value, node, extra) => {
          //console.info(node)
          return false;
        },
        getPopupContainer: () => document.body,
      },
    },
    { label: "编号", field: "number", component: "Input",
      rules: [
        { required: true, trigger: 'blur' },
        { pattern: /^[A-Z][0-9][0-9]/, message: '格式不对，应以大写字母+两位数字；（如：L14）。', trigger: 'blur'  }
      ],
      componentProps: ({formModel}) => {
        return {
          onInput: (e) => {
             formModel.number = e.target.value.toUpperCase();
          },
          autoComplete: 'off',
          maxlength: 3
        }
      }
    },
    { label: "副标题", field: "sub", component: "Input",
      rules: [
        { required: true },
        { pattern:  /[\u4e00-\u9fa5A-Za-z0-9]+$/, message: '不能包含特殊字符！' }
      ],
      componentProps: {
        autoComplete: 'off',
      }
    },
    { label: "主标题", field: "title", component: "Input", required: true,
      componentProps: {
        autoComplete: 'off',
      }
     },
    { label: "行程天数", field: "days", component: "InputNumber", required: true, defaultValue: 6,
      componentProps: { 
        placeholder: " ", autoComplete: 'off', 
      } 
    },
    { label: "截止天数", field: "isGuestEnd", component: "InputNumber", required: true, defaultValue: 3,
      componentProps: { 
        placeholder: " ", autoComplete: 'off', 
      } 
    },
    { label: "收客计调", field: "skrs", component: "JDictSelectTag", required: true,
      componentProps: {
        dictCode: "sys_user,realname,id@departSales",
        mode: "multiple",
        maxTagCount: 4,
        placeholder: "请选择",
        showSearch: true
      },
    },
    { label: "排序", field: "orders", component: "InputNumber", componentProps: { placeholder: " " } },
  ],
  labelWidth: 90,
  baseColProps: {span: 22},
  showActionButtonGroup: false,
});

const isUpdate = ref(true);
//表单赋值
const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
  setModalProps({confirmLoading: false});
  isUpdate.value = !!data?.isUpdate;
  await resetFields()
  if (isUpdate.value) {
    await queryById({id: data?.id}).then((res) => {
      if (res.success) {
        let data = res.result;
        let skrs = data.skrIds && data.skrIds.split(",").filter(item => item);
        console.info(skrs);
        data['skrs'] = skrs
        setFieldsValue(data)
      }
    });
  }
});
//标题
const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

//表单提交事件
async function handleSubmit() {
  try {
    setModalProps({confirmLoading: true});
    const values = await validate();
    await add(values).then((res) => {
      if (res.success) {
        $message.createMessage.success(res.message);
        //关闭弹窗
        closeModal();
        emit("success")
      } else {
        $message.createMessage.warning(res.message);
      }
    });
  } catch (e) {
    console.log(e);
  } finally {
    setModalProps({confirmLoading: false});
  }
}

</script>

<style lang="less" scoped>

</style>
